package com.example.project.controller;

import com.example.project.config.SystemConfig;
import com.example.project.enums.RoleEnum;
import com.example.project.utils.SecurityUtils;
import com.example.project.vo.model.*;
import com.example.project.entity.User;
import com.example.project.service.LoginService;

import com.example.project.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Api(tags = "登入、退出、注册")
@RestController
@RequestMapping("/system")
public class LoginController {

    @Resource
    private SystemConfig systemConfig;

    @Resource
    private UserService userService;

    @Resource
    private LoginService loginService;


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<Map<String, Object>> login(@RequestBody UserDTO userDTO) throws Exception {
        Map<String, Object> login = loginService.login(userDTO);
        return Result.success(login);
    }

    @GetMapping("/logout")
    @ApiOperation("用户退出")
    public Result<Void> logout(HttpServletResponse response) {
        loginService.logout(response);
        return Result.success();
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<Void> register(@RequestBody RegisterVo registerVo) {
        User user = new User();

        user.setUserName(registerVo.getUserName());
        user.setPassword(SecurityUtils.getMd5(registerVo.getPassword()));
        user.setRole(registerVo.getRole());
        user.setPhone(registerVo.getPhone());

        userService.insert(user);
        return Result.success();
    }

    @ApiOperation("系统配置")
    @GetMapping("/systemConfig/detail")
    public Result<SystemConfig> systemConfigDetail() {
        RoleEnum[] roleEnums = RoleEnum.values();
        systemConfig.getRoles().clear();
        for (RoleEnum roleEnum : roleEnums
        ) {
            systemConfig.getRoles().add(new Radio(roleEnum.name(), roleEnum.roleName));
        }
        return Result.success(systemConfig);
    }


    @ApiOperation("发送邮件code")
    @PostMapping("/getEmailCode")
    public Result<?> sendEmailCode(@RequestParam String email){
        loginService.sendEmailCode(email);
        return Result.success();
    }

    @ApiOperation("修改密码")
    @PostMapping("/changePassword")
    public Result<?> changePassword(ChangePasswordVo changePasswordVo){
        loginService.changePassword( changePasswordVo);
        return Result.success();
    }



}
